import sys
import requests
import uuid
import json
import puremagic
import re

def upload_image(image: dict) -> str:
    upload_url = "http://www.aderversa.xyz:8080/api/v1/upload/image"
    response = requests.post(upload_url, files=image)
    if response.status_code == 200:
        return get_url(response.content)
    return ""

def get_url(response_content) -> str:
    response_str = response_content.decode("utf-8")
    try:
        response_data = json.loads(response_str)
        _url = response_data.get("url")
        return _url
    except json.JSONDecodeError as e:
        return ""

def write_data_to_stdout(data: bytes):
    sys.stdout.buffer.write(data)
    sys.stdout.buffer.flush()

def read_data_from_stdin() -> bytes:
    return sys.stdin.buffer.read()

def data_is_http_link(data: bytes) -> bool:
    try:
        link = data.rstrip().decode('utf-8')
        pattern = re.compile(r'^https?:\/\/')
        return pattern.match(link)
    except Exception: # 发送异常说明不是HTTP或HTTPS链接
        return False

def data_is_filename(data: bytes) -> bool:
    try:
        filename = data.rstrip().decode('utf-8')
        pattern = re.compile(r'^file:\/\/\/')
        return pattern.match(filename)
    except Exception:
        return False

def from_data_to_mimetype(data: bytes) -> str:
    return puremagic.from_string(data, mime=True)

def from_mimetype_to_suffix(mimetype: str) -> str:
    if mimetype == "image/png":
        return ".png"
    elif mimetype == "image/jpeg":
        return ".jpg"
    elif mimetype == "image/gif":
        return ".gif"
    return ""


def handle_binary_data(data: bytes) -> str:
    mimetype = from_data_to_mimetype(data)
    filename = str(uuid.uuid4())
    suffix = from_mimetype_to_suffix(mimetype)
    image = {
        "file": (filename + suffix, data, mimetype),
    }
    return upload_image(image)

